<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\handlers\backend;

use Yii;
use yii\base\ActionEvent;
use yii\web\Response;
use common\models\Admin;
use common\models\TlogService;
use common\handlers\BaseHandler;
use builder\helper\Arr;

/**
 * 请求完成后, 记录操作日志
 * @author cleverstone
 * @since ym2.0
 */
class AfterActionRecordOperationLog extends BaseHandler
{
    /**
     * @param ActionEvent $event
     * @throws \Throwable
     */
    public function run($event)
    {
        $request = $this->request;
        $isOpenTlog = Yii::$app->setting->read('SYS.SYS_TLOG', 1);

        if ($request->isPost && $isOpenTlog) {
            /** @var Response $response */
            $response = $event->result;
            $result = $response->data;
            if (is_array($result)) {
                $message = !empty($result['msg']) ? $result['msg'] : '-';
            } else {
                $message = (string)$result;
            }

            /** @var \stdClass $params */
            $params = $event->data;

            /** @var Admin $user */
            $user = $params->user;
            $permissionName = $params->permissionName;
            $canPermissions = Arr::index($params->canPermissions, 'link');

            $item = $canPermissions[$permissionName];
            TlogService::write($user->id, $permissionName, $item['desc'] ?: $item['name'], $message);
        }
    }
}